package com.wg.core.time;

import cn.hutool.cron.task.Task;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 定时任务调度器：管理并执行多个定时任务
 *
 * @author 少爷123
 */
public class TaskScheduler {
    private static final Log log = LogFactory.get();
    private final Map<String, TimedTask> scheduledTasks = new HashMap<>();
    private long lastCheckTime;

    public void schedule(String taskId, int intervalMs, Task taskHandler) {
        scheduledTasks.put(taskId, new TimedTask(taskId, intervalMs, taskHandler));
    }

    public void cancelSchedule(String taskId) {
        scheduledTasks.remove(taskId);
    }

    public void executeDueTasks() {
        final long currentTime = System.currentTimeMillis();

        if (currentTime - lastCheckTime < 5) {
            return;
        }
        lastCheckTime = currentTime;

        for (Map.Entry<String, TimedTask> entry : scheduledTasks.entrySet()) {
            TimedTask task = entry.getValue();
            try {
                task.executeIfDue(currentTime);
            } catch (Exception e) {
                log.error("Error executing task: {}, e:{}", task.getTaskId(), e);
            }
        }
    }
}
